package cn.aishua.ui.myKaka.task;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import cn.aishua.network.HttpRequestUtil;
import cn.aishua.ui.MainActivityGroup;
import cn.aishua.ui.myKaka.CreditExchangeActivity;
import cn.aishua.ui.vendor.VendorDetailActivity;
import cn.aishua.util.FormatConverter;
import cn.aishua.util.NetworkState;
import cn.aishua.util.SharedPrefConst;
import cn.aishua.util.ViewHelper;

public abstract class DataExchangeAsyncTask
    extends AsyncTask<String, Void, HttpResponse>
{

    ProgressDialog dialog;

    protected Context context;

    String progressDialogTitle;

    String promotion = "";

    public DataExchangeAsyncTask()
    {
    }

    public DataExchangeAsyncTask(Context context, String progressDialogTitle)
    {
        this.context = context;
        this.progressDialogTitle = progressDialogTitle;
    }

    @Override
    protected void onPreExecute()
    {
        ViewHelper.hideKeyboard( (Activity) context );
        if( progressDialogTitle != null )
        {

            dialog = new ProgressDialog( context );
            dialog.setTitle( progressDialogTitle );
            dialog.setMessage( "正在连接服务器" );
            dialog.setButton( "取消", new OnClickListener()
            {

                public void onClick( DialogInterface dialog, int which )
                {
                    dialog.dismiss();
                    //                    HttpRequestUtil.getInstance().abort();
                }
            } );
            //            dialog.show();
        }
    }

    @Override
    protected HttpResponse doInBackground( String... params )
    {
        HttpResponse res = null;
        try
        {
            waitForNavibar();
            if( NetworkState.isAvailable( context ) )
            {
                res = sendRequest( params );
            }
            else
            {
                promotion = "没有网络连接";
            }
        }
        catch( RuntimeException e )
        {
            promotion = e.getMessage();
        }
        return res;
    }

    private void waitForNavibar()
    {
        Activity activity = (Activity) context;
        if( activity.getParent() != null && activity.getParent() instanceof MainActivityGroup )
        {
            MainActivityGroup main = (MainActivityGroup) activity.getParent();
            while( main.clickArea.getVisibility() != View.GONE )
            {

            }
            handler.sendEmptyMessage( 0 );
        }
        handler.sendEmptyMessage( 0 );
    }

    @Override
    protected void onPostExecute( HttpResponse httpRes )
    {
        if( dialog != null )
        {
            dialog.dismiss();
        }

        if( httpRes == null ) // timeout case
        {
            showToast( promotion );
            return;
        }

        try
        {
            int statusCode = httpRes.getStatusLine().getStatusCode();
            Log.d( "DataExchangeAsncTask", "status code of http: " + statusCode );
            if( HttpStatus.SC_OK == statusCode )
            {
                HttpEntity entity = httpRes.getEntity();
                String strJson = EntityUtils.toString( entity );
                Log.d( "string response: ", strJson );
                handleSuccResponse( strJson );
            }
            else if( HttpStatus.SC_FORBIDDEN == statusCode )
            {
                //                String strResult = MyKakaTestJsonData.VENDOR_DELETED;

                String strResult = EntityUtils.toString( httpRes.getEntity() );
                Log.d( "string response: ", strResult );
                JSONObject jsonObj = new JSONObject( strResult );

                if( jsonObj.has( "bank_card" ) ) // handling when bank cards is empty , this is still considered as success
                {
                    handleSuccResponse( strResult ); // pass empty string as parameter
                }
                else if( jsonObj.has( "error" ) )
                {
                    String errorMsg = jsonObj.getString( "error" );
                    showToast( errorMsg );

                    if( context instanceof MainActivityGroup )
                    {
                        handleSuccResponse( strResult );
                    }
                }
                else if( jsonObj.has( "msg" ) )
                {
                    String errorMsg = jsonObj.getString( "msg" );
                    showToast( errorMsg );

                    if( context instanceof VendorDetailActivity )// vendor is deleted from server, go back to last page
                    {
                        VendorDetailActivity activity = (VendorDetailActivity) context;
                        activity.finish();
                    }
                    else if( context instanceof CreditExchangeActivity ) // user hasn't set the exchange card
                    {
                        handleSuccResponse( strResult );
                    }

                    // abort request
                    //                    HttpRequestUtil.getInstance().abort();
                }
            }
            else if( HttpStatus.SC_INTERNAL_SERVER_ERROR == statusCode )
            {
                showToast( "服务器暂时无法响应" );
            }
            else
            {
                showToast( "非正常退出，请重新登录" );
                HttpRequestUtil.getInstance().clearCookies();

                SharedPreferences sharedPref = context.getSharedPreferences( "userInfo", Context.MODE_PRIVATE );
                Editor mEditor = sharedPref.edit();
                mEditor.remove( SharedPrefConst.SHARED_PREF_BOOL_USER_IS_LOGIN );
                mEditor.commit();

                // go to login activity
                Intent intent = new Intent( context, MainActivityGroup.class );
                intent.putExtra( MainActivityGroup.TAB, MainActivityGroup.TAG_USER_INFO );
                context.startActivity( intent );
                ( (Activity) context ).finish();

            }
            httpRes.getEntity().consumeContent();

            // abort request
            //            HttpRequestUtil.getInstance().abort();
        }
        catch( JSONException e )
        {
            Log.e( "DataExchangeAsynTask", e.getMessage() );
        }
        catch( ParseException e )
        {
            Log.e( "DataExchangeAsynTask", e.getMessage() );
        }
        catch( IOException e )
        {
            Log.e( "DataExchangeAsynTask", e.getMessage() );
        }
        catch( Exception e )
        {
            Log.e( "DataExchangeAsynTask", "Unkonwn Exception" );
        }

    }

    private void showToast( String text )
    {
        if( FormatConverter.isNotEmptyString( text ) )
        {
            Toast.makeText( context, text, Toast.LENGTH_LONG ).show();
        }
    }

    //    private String getStrJsonFromHttpEntity( HttpEntity entity ) throws UnsupportedEncodingException, IOException
    //    {
    //        if( entity != null )
    //        {
    //            String charset = EntityUtils.getContentCharSet( entity ) == null ? HttpRequestUtil.CHARSET_UTF8
    //                : EntityUtils.getContentCharSet( entity );
    //            return new String( EntityUtils.toByteArray( entity ), charset );
    //        }
    //        else
    //        {
    //            return "";
    //        }
    //    }

    protected abstract HttpResponse sendRequest( String... params );

    protected abstract void handleSuccResponse( String strJson ) throws Exception;

    Handler handler = new Handler()
    {
        public void handleMessage( android.os.Message msg )
        {
            if( dialog != null )
            {
                dialog.show();
            }
        };
    };
}
